<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Application\Controller;

use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Authentication\AuthenticationService;
use Zend\Session\Container;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        $auth = new AuthenticationService();
        if ($auth->getIdentity()) {
            // it means logged-in user.
            $layout = $this->layout()->setVariable('user', $this->getUserFromSession());
            $view = new ViewModel(array('user' => $this->getUserFromSession()));
            $layout->setTemplate('layout/loggedin');
            $view->setTemplate("/application/user/home");
            return $view;

        } else {

            $isAjax =  $this->getRequest()->getQuery("ajax");
            if ($isAjax) {
                $this->redirect()->toUrl("/loginAjax");
            } else {

                $recommender =  $this->getRequest()->getQuery("inviter");

                $secret =  $this->getRequest()->getQuery("secret");


                $userDao = $this->getServiceLocator ()
                    ->get ( 'user' );

                if($recommender == null){
                    $view = new ViewModel(array('recommender' => false));
                    $view->setTemplate("/application/index/index");
                    $this->layout("/layout/layout");
                    return $view;
                } else {

                    $recommendedUser = $userDao->recommendedUser($recommender, $secret);

                    if($recommendedUser != null ){
                        $users = $userDao->getRecentlyAddedUser();
                        $view = new ViewModel(array('users' => $users));
                        $view->setVariable('recommender', $recommendedUser);
                        return $view;
                    }
                }
            }
        }
        return null;
    }



    
    private function getUserFromSession(){

    	$auth = new AuthenticationService();
    	$userSession = new Container('user');
    	if($userSession->user != null){
    		return $userSession->user;
    	} else {
    		return $auth->getIdentity();
    	}

    }





}
